import React from 'react';
import ReactDOM from 'react-dom';
import findIndex from "lodash/findIndex";
import uniqBy from "lodash/uniqBy";
import LzEditor from 'react-lz-editor'
import constants from '../../common/constants'
import {Base64} from "js-base64";
import hmacsha1 from "hmacsha1";
import md5 from "md5";

export default class LzEditorCom extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // htmlContent: `<h1>Yankees, Peeking at the Red Sox, Will Soon Get an Eyeful</h1>
            //     <p>Whenever Girardi stole a glance, there was rarely any good news for the Yankees. While Girardi’s charges were clawing their way to a split of their four-game series against the formidable Indians, the Boston Red Sox were plowing past the rebuilding Chicago White Sox, sweeping four games at Fenway Park.</p>`,
            markdownContent: "## HEAD 2 \n markdown examples \n ``` welcome ```",
            responseList: []
        }
        this.onChange = this.onChange.bind(this);
        this.getSignature = this.getSignature.bind(this);
        this.getPolicy = this.getPolicy.bind(this);
    }

    getPolicy(fileName) {
        let now = new Date();
        let afterHour = new Date(now.getTime() + 1 * 60 * 60 * 1000); //expiration date time
        let policy = Base64.encode(JSON.stringify({
            "bucket": "devopee",
            "save-key": "./" + fileName,
            "expiration": Math.round(afterHour.getTime() / 1000),
            "date": now
        }));
        return policy;
    }

    getSignature(fileName) {
        let now = new Date();
        let h = hmacsha1('19931944122b23f77681b6ab765648f8', 'POST&/upyun-temp/' + fileName + '&' + now);
        let Signature = Base64.encode(h);
        return Signature;
    }

    onChange(info) {
        let currFileList = info.fileList;
        currFileList = currFileList.filter((f) => (!f.length));
        let url = constants.imageUrlFix;

        //Read remote address and display.
        //读取远程路径并显示链接
        currFileList = currFileList.map((file) => {
            if (file.response) {
                // concat url
                // 组件会将 file.url 作为链接进行展示
                file.url = url + file.response[file.response.length-1].fileUrl;
            }
            if (!file.length) {
                return file;
            }
        });
        let _this = this;

        // filtering successed files
        //按照服务器返回信息筛选成功上传的文件
        currFileList = currFileList.filter((file) => {
            //multiple uploading?
            //根据多选选项更新添加内容
            let hasNoExistCurrFileInUploadedList = !~findIndex(_this.state.responseList, item => item.name === file.name)
            if (hasNoExistCurrFileInUploadedList) {
                if (!!_this.props.isMultiple == true) {
                    _this.state.responseList.push(file);
                } else {
                    _this.state.responseList = [file];
                }
            }
            return !!file.response || (!!file.url && file.status == "done") || file.status == "uploading";
        });
        currFileList = uniqBy(currFileList, "name");
        if (!!currFileList && currFileList.length != 0) {
            this.setState({responseList: currFileList});
        }
        _this.forceUpdate();
    }
    receiveHtml = (content) => {
        this.props.getGoodDesc(content);
        this.setState({
            responseList: []
        });
    }

    render() {
        let policy = "";
        const uploadProps = {
            action: constants.fileServer,
            onChange: this.onChange,
            listType: 'picture',
            fileList: this.state.responseList,
            data: (file) => {

            },
            multiple: false,
            // beforeUpload: this.beforeUpload,
            showUploadList: true
        }
        return (
            <div>
                {/*<div>Editor demo 1 (use default html format ):*/}
                {/*</div>*/}
                <LzEditor active={true}
                          importContent={this.props.importContent}
                          cbReceiver={this.receiveHtml}
                          uploadProps={uploadProps}
                />
                <br/>
                {/*<div>Editor demo 2 (use markdown format ):*/}
                {/*</div>*/}
                {/*<LzEditor*/}
                    {/*active={true}*/}
                    {/*importContent={this.state.markdownContent}*/}
                    {/*cbReceiver={this.receiveMarkdown}*/}
                    {/*image={false}*/}
                    {/*video={false}*/}
                    {/*audio={false}*/}
                    {/*convertFormat="markdown"/>*/}
            </div>
        );
    }
}
